<template>
  <!-- 容器 -->
  <div class="login-container">
    <!-- 注册的大盒子 -->
    <div class="box-login">
      <!-- 注册内部的标题区域 -->
      <div class="box-login-title"></div>
      <el-form :model="loginFrom" :rules="loginFromRules" ref="loginFromRef">
        <el-form-item prop="username">
          <el-input v-model="loginFrom.username" placeholder="请输入用户名" prefix-icon="el-icon-user"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="loginFrom.password"
            placeholder="请输入密码"
            prefix-icon="el-icon-lock"
            type="password"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="btn-login" @click="login">登录 </el-button>
          <el-link type="info" @click="$router.push('/reg')">去注册</el-link>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
// import axios from 'axios'
import { loginApi } from '../api/user.js'

export default {
  name: 'Login',
  data() {
    return {
      loginFrom: {
        username: '',
        password: ''
      },
      loginFromRules: {
        username: [
          { required: true, message: '用户名是必填项', trigger: 'blur' },
          { pattern: /^[a-zA-Z0-9]{2,10}$/, message: '用户名必须是2-10位字母或数子', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码是必填项', trigger: 'blur' },
          { pattern: /^\S{6,15}$/, message: '密码必须是6-15位非空字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    login() {
      this.$refs.loginFromRef.validate(async valid => {
        if (!valid) return
        // const { data: res } = await axios.post('http://www.liulongbin.top:3008/api/login', this.loginFrom)
        const { data: res } = await loginApi(this.loginFrom)
        if (res.code !== 0) return this.$message.error(res.message)
        this.$message.success(res.message)
        console.log(res.token)
        this.$store.commit('user/updateToken', res.token)
        this.$router.push('/')
      })
    }
  }
}
</script>

<style lang="less" scoped>
.login-container {
  height: 100%;
  background: url('../assets/images/login_bg.jpg') no-repeat;
  background-size: cover;

  .box-login {
    width: 400px;
    height: 270px;
    padding: 0 20px;
    background-color: #fff;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    border-radius: 3px;
    .box-login-title {
      height: 60px;
      background: url('../assets/images/login_title.png') no-repeat;
      background-position: center;
    }
    .btn-login {
      width: 100%;
    }
  }
}
</style>
